package com.burgeon.backend.SHOP.service.Impl;

import com.burgeon.backend.SHOP.entity.Order;
import com.burgeon.backend.SHOP.entity.OrderItem;
import com.burgeon.backend.SHOP.entity.presell.Presell;
import com.burgeon.backend.SHOP.mappers.AppTemplateMapper;
import com.burgeon.backend.SHOP.mappers.OrderMapper;
import com.burgeon.backend.SHOP.service.AppTemplateService;
import com.burgeon.backend.SHOP.service.SystemService;
import com.burgeon.backend.WeChat.WeChatMessageConnector;
import com.burgeon.backend.entity.Coupon;
import com.burgeon.backend.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AppTemplateServiceImpl implements AppTemplateService {

    @Autowired
    private WeChatMessageConnector weChatMessageConnector;
    @Autowired
    private SystemService systemService;
    @Autowired
    private AppTemplateMapper appTemplateMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WechatService wechatService;


    @Override
    public void SendExpense(String oid,String uid,String openid, String token){

        Order order = orderMapper.FindLatestOrder(oid, uid, token);

        //预售单处理
        if (order.getOrderId().substring(order.getOrderId().length()-1).equals("Y")){
            //查询预售单
            Presell presell = orderMapper.FindPresellByOid(order.getId());
            order.setTotalPrice(presell.getRem());
            //更改支付价格
        }
        String ACCESS_TOKEN = systemService.GetAccesToken(token);
        String url ="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+ACCESS_TOKEN;
        String templateId = appTemplateMapper.GetTemplate(token).getTemplate1();
        List<OrderItem> orderItems = orderMapper.FindOrderItemByOid(order.getId());
        String goodsName = orderItems.get(0).getGoodsTitle();

        if (orderItems.size()>1){
            goodsName = goodsName+"...";
        }

        if (goodsName.length()>19){
            goodsName = goodsName.substring(0,17)+"...";
        }

        String data = ExpenseMessage(goodsName,templateId,openid,order,token).trim();
        String row = weChatMessageConnector.Send(url, data);

        System.err.println(row);

    }

    @Override
    public void SendExchangeCoupon(Coupon coupon, String phone, String openid, String token) {
        String ACCESS_TOKEN = systemService.GetAccesToken(token);
        String url ="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+ACCESS_TOKEN;
        String templateId = appTemplateMapper.GetTemplate(token).getTemplate2();
        String data = ExchangeCouponMessage(coupon,templateId,openid,token);
        String row = weChatMessageConnector.Send(url, data);

        System.err.println(row);

    }

    @Override
    public void sendDueNotice(String token,String endDate,String openId) {
        String ACCESS_TOKEN = wechatService.GetAccesTokenByAccount(token);
        String url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ACCESS_TOKEN;
        String templateId = appTemplateMapper.GetTemplateIfo(token).getTemplateid11();
        String data = sendDueNoticeTemplate(templateId,endDate,openId);
        String row = weChatMessageConnector.Send(url, data);

        System.err.println(row);

    }

    @Override
    public void sendBirthdayNotice(String openid, String token, String phone,String name) {
        String ACCESS_TOKEN = wechatService.GetAccesTokenByAccount(token);
        String url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ACCESS_TOKEN;
        String templateId = appTemplateMapper.GetTemplateIfo(token).getTemplateid1();
        String data = sendBirthdayNoticeTemplate(templateId,phone,openid,name);
        String row = weChatMessageConnector.Send(url, data);

        System.err.println(row);
    }

    private String sendBirthdayNoticeTemplate(String templateId,String phone,String openid,String name){
        return "{  \"touser\":\"" + openid + "\",\n" +
                "           \"template_id\":\"" + templateId + "\",\n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":\"生日来临，好礼相送，请在规定时间内领取您的生日好礼\"," +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword1\":{\n" +
                "                       \"value\":\"" + phone + "\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword2\": {\n" +
                "                       \"value\":\"" + name + "(先生/女士)的生日好礼\",\n" +
                "                        \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":\"我们用心提升我们的服务,只为您100分满意！\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   } }   }";
    }


    private String sendDueNoticeTemplate(String templateId,String endDate,String openId){
        return "{  " +
                "\"touser\": \""+openId+"\"," +
                "\"template_id\":\"" + templateId + "\",\n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":\"您的Plus会员服务即将到期，为了不影响您的正常使用优惠，请您及时续费\"," +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword1\":{\n" +
                "                       \"value\":\"" + "Plus会员" + "\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword2\": {\n" +
                "                       \"value\":\"" + endDate + "\",\n" +
                "                        \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":\"我们用心提升我们的服务,只为您100分满意！\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   } }   }";
    }


/**
 * 兑换优惠券参数
 */
    private String ExchangeCouponMessage(Coupon coupon,String templateId,String openid,String token){
        return "{" +
                "  \"touser\": \""+openid+"\"," +
                "  \"template_id\": \""+templateId+"\"," +
                "  \"page\": \"pages/member/ticketList/ticketList?token="+token+"&empName=''\"," +
                "  \"lang\":\"zh_CN\"," +
                "  \"data\": {" +
                "      \"thing2\": {" +  //名称
                "          \"value\": \""+coupon.getName()+"\"" +
                "      }," +
                "      \"time3\": {" +  //过期时间
                "          \"value\": \""+coupon.getDateend()+"\"" +
                "      }," +
                "      \"time7\": {" +  //领取时间
                "          \"value\": \""+coupon.getCreation()+"\"" +
                "      } " +
                "  }" +
                "}";

    }

    /**
     * 消费提醒参数
     * @return
     */
    private String ExpenseMessage(String goodsName,String templateId,String openid,Order order,String token){

        return "{" +
                "  \"touser\": \""+openid+"\"," +
                "  \"template_id\": \""+templateId+"\"," +
                "  \"page\": \"pages/userStart/userStart?token="+token+"&empName=''\"," +
                "  \"lang\":\"zh_CN\"," +
                "  \"data\": {" +
                "      \"thing1\": {" +  //品名
                "          \"value\": \""+goodsName+"\"" +
                "      }," +
                "      \"amount3\": {" +  //金额
                "          \"value\": \""+order.getTotalPrice()+"\"" +
                "      }," +
                "      \"thing4\": {" +  //收货地址
                "          \"value\": \""+addressSet(order.getAddress())+"\"" +
                "      } ," +
                "      \"date5\": {" + //下单时间
                "          \"value\": \""+order.getOrderTime()+"\"" +
                "      }," +
                "      \"character_string6\": {" + //订单编号
                "          \"value\": \""+order.getOrderId()+"\"" +
                "      }" +
                "  }" +
                "}";
    }
    private String addressSet(String address){

       StringBuilder data = new StringBuilder(address);

        if (address.length()>20){
            data = new StringBuilder();
            String[] arr = address.split("市");
            if (arr.length>1){
                for (int i=1;i<arr.length;i++){

                    data.append(arr[i]);
                }
            }
        }

        if (data.length()>20){
         return data.substring(0,17)+"...";
        }

        return data.toString();
    }




}
